package com.mxy.myapplication.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.mxy.myapplication.R;
import com.mxy.myapplication.pojo.ParcelableTest;
import com.mxy.myapplication.pojo.Pojo2;
import com.mxy.myapplication.util.Util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 扫描二维码,生成二维码界面
 */

public class ScanActivity extends BaseActivity implements View.OnClickListener, View.OnLongClickListener {

    private View made;
    private View scan;
    private EditText editText;
    private ImageView imageView;
    private final int qrcodeBitmapPx = 800;//生成的二维码图片分辨率

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_qrcode);
        initView();
    }

    private void initView() {
        made = findViewById(R.id.made);
        scan = findViewById(R.id.scan);
        made.setOnClickListener(this);
        scan.setOnClickListener(this);

        editText = (EditText) findViewById(R.id.editText);
        imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setLongClickable(true);
        imageView.setOnLongClickListener(this);

        ParcelableTest parcelableTest = getIntent().getParcelableExtra("Parcelable");
        System.out.println(parcelableTest.getName());
        System.out.println(parcelableTest.getAge());

        for (Pojo2 pojo2 : parcelableTest.getPojo2s()) {
            System.out.println(pojo2.getHight());
        }
    }

    /**
     * @param str 基于str内容生成QRcode
     * @return bitmap对象，可能为null
     */
    private Bitmap CreateQRcodeAsBitmap(String str) {
        Bitmap qrCodebitmap = null;
        BitMatrix bitMatrix = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            //强烈建议不要在声称二维码的内容上使用汉字，影响扫描识别效果
            bitMatrix = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, qrcodeBitmapPx, qrcodeBitmapPx);
            // 使用 ZXing Android Embedded 要写的代码，简单不？如果不用ZXing Android Embedded的话...哼哼~
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            bitMatrix = deleteWhite(bitMatrix);//去掉图片四周留白
            qrCodebitmap = barcodeEncoder.createBitmap(bitMatrix);
            Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
            qrCodebitmap = addLogo(qrCodebitmap, logo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCodebitmap;
    }


    /**
     * 将入BitMatrix对象，将其图片的四周留白去掉
     *
     * @param matrix BitMatrix对象
     * @return
     */
    private BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 10;
        int resHeight = rec[3] + 10;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0] - 5, j + rec[1] - 5)) {
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }

    /**
     * 在二维码中间添加Logo图案
     */
    private static Bitmap addLogo(Bitmap qrCodeBitmap, Bitmap logo) {
        if (qrCodeBitmap == null) {
            return null;
        }
        if (logo == null) {
            return qrCodeBitmap;
        }
        //获取图片的宽高
        int srcWidth = qrCodeBitmap.getWidth();
        int srcHeight = qrCodeBitmap.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();
        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }
        if (logoWidth == 0 || logoHeight == 0) {
            return qrCodeBitmap;
        }
        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(qrCodeBitmap, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
            canvas.save();
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }
        return bitmap;
    }

    /**
     * 调起zxing扫描界面
     */
    private void scanBarcodeCustomLayout() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setCaptureActivity(MyScanActivity_Portrait.class);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
        integrator.setPrompt("扫描二维码/条形码");
        integrator.setBarcodeImageEnabled(true);
        integrator.setOrientationLocked(true);//是否允许横竖屏切换
        integrator.setBeepEnabled(true);//是否发出声效
        integrator.initiateScan();
    }

    /**
     * 调起自定义扫描界面
     */
    private void callCustomScannerActivity() {
        new IntentIntegrator(this).setOrientationLocked(false).setCaptureActivity(Customer_Scanner_activity.class).initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() != null) {
                editText.setText(result.getContents());
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == made) {
            if (editText.getEditableText().toString().trim().equals("")) {
                Util.showToast(this, "请输入内容以生成二维码");
                return;
            } else {
                Bitmap bitmap = CreateQRcodeAsBitmap(editText.getEditableText().toString().trim());
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                } else {
                    Util.showToast(this, "生成二维码失败");
                }
            }
        }
        if (v == scan) {
//            scanBarcodeCustomLayout();
            callCustomScannerActivity();
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if (v == imageView) {
            if (imageView.getDrawable() != null) {
                showDialog();
            } else {
                Util.showToast(this, "请先生成二维码图片");
            }
        }
        return false;
    }

    /**
     * 弹出对话框
     */
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setMessage("保存这张二维码图片到相册么?");
        builder.setTitle("保存二维码");
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                File file = new File(Environment.getExternalStoragePublicDirectory("DCIM" + File.separator + "Camera" + File.separator).getPath());
                if (!file.exists()) {
                    boolean canCreateDir = file.mkdirs();
                    if (!canCreateDir) {//文件夹创建失败
                        Util.showToast(ScanActivity.this, "保存失败");
                        return;
                    }
                }
                try {
                    //保存二维码图片
                    String bitmapaddress = file.getPath() + File.separator + Util.getUUid() + ".jpg";
                    Bitmap qrCodeBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
                    BufferedOutputStream bof = new BufferedOutputStream(new FileOutputStream(bitmapaddress));
                    qrCodeBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bof);
                    bof.close();
                    //通知系统图片sqlite更新刚保存的图片文件
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(bitmapaddress))));
                    Util.showToast(ScanActivity.this, "保存成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    Util.showToast(ScanActivity.this, "保存失败");
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }
}